package com.gpj.sqlbuilder.template;

import com.gpj.sqlbuilder.constants.Constants;
import com.gpj.sqlbuilder.utils.TextUtils;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @className BaseTemplate
 * @description TODO
 * @author GPJ
 * @date 2021/4/16 20:47
 * @version 1.0
 **/
@Getter
public abstract class ElementTemplate extends BaseTemplate{
	private static final String ELEMENT_TEMPLATE_LOOP_MARK = "for";
	private static final String ELEMENT_TEMPLATE_CHOOSE_MARK = "if";
	private static final String ELEMENT_TEMPLATE_FORMAT_MARK = "format";

	protected int contentStart;
	protected int contentEnd;

	private Map<String, String> attributes = new HashMap<>();

	public ElementTemplate(int start, int tail, Template parent) {
		super(start, tail, parent);
		contentStart = TextUtils.findEndMarkIndex(this.template,
				Constants.TEMPLATE_START_MARK, Constants.TEMPLATE_END_MARK, 0) + 1;

		contentEnd = template.length() - getTailMark().length();

		String ekeAttribute = template.substring(getStartMark().length() - 1, contentStart - 1);

		// 解析属性
		String[] attributes = ekeAttribute.split("\"");
		if(attributes != null && attributes.length > 0){
			for (int i = 0; i < attributes.length; i+=2) {
				String key = attributes[i].trim();
				String value = attributes[i+1];
				this.attributes.put(TextUtils.substr(0,-1, key),
						TextUtils.substr(0,value.length(), value));
			}
		}
	}

	public String getAttribute(String attributeName, String defalut){
		String itemName = attributes.get(attributeName);
		if(StringUtils.isNotBlank(itemName)){
			return itemName;
		}
		return defalut;
	}

	abstract protected String getStartMark();

	abstract protected String getTailMark();

	public static ElementTemplate createElementTemplate(int start, int tail, Template template){
		StringBuffer text = template.getTemplate();
		if(matchMark(start, text, ELEMENT_TEMPLATE_FORMAT_MARK)){
			return new FormatTemplate(start, tail + ELEMENT_TEMPLATE_FORMAT_MARK.length() + 1, template);
		}else if(matchMark(start, text, ELEMENT_TEMPLATE_LOOP_MARK)){
			return new LoopTemplate(start, tail + ELEMENT_TEMPLATE_LOOP_MARK.length() + 1, template);
		}else if(matchMark(start, text, ELEMENT_TEMPLATE_CHOOSE_MARK)){
			return new ChooseTemplate(start, tail + ELEMENT_TEMPLATE_CHOOSE_MARK.length() + 1, template);
		}
		throw new RuntimeException("未找的匹配的模板类型！");
	}

	private static boolean matchMark(int start, StringBuffer text, String startMark){
		String str = text.substring(start + 1, start + startMark.length() + 1);
		return StringUtils.equals(startMark, str);
	}
}
